package com.xinghen.common.util;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.awt.image.BufferedImage;
import java.util.Properties;

/**
 * @author xinghen
 * @ClassName: KaptchaUtil
 * @Package: com.xinghen.common.util
 * @Description 图片验证码工具
 * @create 2018-04-19 13:55
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class KaptchaUtil {

    /**
     * 获取图片验证码工具
     *
     * @return
     */
    public static Producer defaultKaptcha() {
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.border.color", "no");
        properties.setProperty("kaptcha.border.color", "220,227,232");
        properties.setProperty("kaptcha.textproducer.char.string", "2345689");
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        properties.setProperty("kaptcha.textproducer.font.size", "16");
        properties.setProperty("kaptcha.image.width", "106");
        properties.setProperty("kaptcha.image.height", "30");
        properties.setProperty("kaptcha.session.key", "kaptchaCode");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.background.clear.from", "white");
        properties.setProperty("kaptcha.background.clear.to", "white");
        properties.setProperty("kaptcha.textproducer.char.space", "5");
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        properties.setProperty("kaptcha.textproducer.font.names", "Verdana");
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }

    /**
     * 获取验证码
     *
     * @return
     */
    public static String getCode() {
        Producer producer = defaultKaptcha();
        return producer.createText();
    }

    /**
     * 获取图片
     *
     * @param code
     * @return
     */
    public static BufferedImage getImage(String code) {
        return defaultKaptcha().createImage(code);
    }


}
